#!/bin/bash
workdir=$(cd $(dirname $0) && pwd || pwd)
rundir=$(pwd)
cd $workdir

args_ip=$(ip -o route get to 8.8.8.8 | sed -n 's/.*src \([0-9.]\+\).*/\1/p')

args_pwd=$1
args_name=$2
#bt_token=$4
#bt_token_crypt=$5
#mods=$4
version=$3
# echo "args_ip=$args_ip"
# echo "args_pwd=$args_pwd"
# echo "args_name=$args_name"

if ((${#@} < 3)); then
  echo "参数不全，重新输入"
  exit 1
fi
# ------------------------
function logOut() {
  DATEALL=$(date +%Y%m%d)
  CMD_ECHO='echo'
  SCRIPT_NAME=$(basename $0)
  if [ -z "$2" ]; then
    logLevel="INFO"
  else
    logLevel=$2
  fi

  LOG_PRINT="eval $CMD_ECHO \"[$SCRIPT_NAME]\" @\`date +\"%Y-%m-%d %T\"\` [$logLevel] :"
  log_file="${SCRIPT_NAME}.log.${DATEALL}"

  $LOG_PRINT "$1" | tee -a $workdir/$log_file
}

function error() {
  logOut "$1" "ERROR"
  # 释放git代理
  gitProxy "stop"
  exit 1
}
function checkProcess() {
  local stepFile="$workdir/setp.txt"
  if [[ "${1}" == "in" ]]; then
    echo "$2" >>"$stepFile"
    return
  fi
  local step="$1"
  grep -q "^$step" "$stepFile"
  return $?
}
function tryGitClone() {
  target="$1"
  Name="$2"
  for i in {1..3}; do
    eval $target
    if [ $? -eq 0 ]; then
      logOut "$Name，clone成功"
      break
    else
      if (($i == 3)); then
        error "$Name，clone失败"
      fi
    fi
  done
}

# -----------------------------------------------------

function package_init() {
  checkProcess "package_init" && return
  if [ -f "/usr/bin/yum" ] && [ -d "/etc/yum.repos.d" ]; then
    PM="yum"
  elif [ -f "/usr/bin/apt-get" ] && [ -f "/usr/bin/dpkg" ]; then
    PM="apt-get"
  fi

  if [ ! -f "/usr/bin/unzip" ]; then
    if [ "${PM}" = "yum" ]; then
      yes | yum install unzip -y && logOut "安装unzip成功" || error "安装unzip失败"
    elif [ "${PM}" = "apt-get" ]; then
      apt-get update
      yes | apt-get install unzip -y && logOut "安装unzip成功" || error "安装unzip失败"

    fi
  fi
  checkProcess "in" "package_init"
}

function firewall() {
  checkProcess "firewall" && return
  # 开放3306端口
  sudo ufw allow 3306 && logOut "允许3306放行成功" || error "允许3306放行失败"
  sudo ufw allow 8085 && logOut "允许8085放行成功" || error "允许8085放行失败"
  sudo ufw allow 3724 && logOut "允许3724放行成功" || error "允许3724放行失败"
  sudo ufw allow 7878 && logOut "允许7878放行成功" || error "允许7878放行失败"
  sudo ufw reload

  checkProcess "in" "firewall"
}

function install() {
    # checkProcess "install" && return
    cd /
    rm -rf /azerothcore
    logOut "版本为$version"
    if [ "$version" = 2 ]; then
        tryGitClone "git clone https://gitee.com/53957105/AzerothCore-wotlk-with-NPCBots.git --branch cn --single-branch azerothcore" "AzerothCore-wotlk-with-NPCBots"
    elif [ "$version" = 1 ]; then
        tryGitClone "git clone https://gitee.com/53957105/AzerothCore-wotlk-with-NPCBots.git --branch cn_dev --single-branch azerothcore" "AzerothCore-wotlk-with-NPCBots"
    else
        tryGitClone "git clone https://gitee.com/53957105/azerothcore-wotlk-github.git --branch cn --single-branch azerothcore" "azerothcore-wotlk-github"
        cd /azerothcore/modules
        tryGitClone "git clone https://gitee.com/53957105/mod-eluna-github.git --branch cn --single-branch mod-eluna" "mod-eluna-github"
        tryGitClone "git clone https://gitee.com/53957105/mod-cfbg-github --single-branch mod-cfbg" "mod-cfbg-github"
        tryGitClone "git clone https://gitee.com/53957105/mod-bg-item-reward-github --single-branch mod-bg-item-reward" "mod-bg-item-reward-github"
        tryGitClone "git clone https://gitee.com/53957105/mod-ah-bot-github --single-branch mod-ah-bot" "mod-ah-bot-github"
    fi
    checkProcess "in" "install"
}

function setEnvAndcompiler() {
    wget --no-check-certificate --timeout=10 --tries=2 -O /azerothcore/deps/deno/bin/deno http://hx.phasercn.com/client-data/deno
    chmod a+x /azerothcore/deps/deno/bin/deno
    # checkProcess "setEnvAndcompiler" && return
    \cp /azerothcore/conf/dist/config.sh /azerothcore/conf/
    /azerothcore/acore.sh install-deps && logOut "install-deps成功" || error "install-deps失败"
    /azerothcore/acore.sh compiler all && logOut "compiler成功" || error "compiler失败"
    checkProcess "in" "setEnvAndcompiler"
}

function mysql_init() {
    # checkProcess "mysql_init" && return
    mysql -uroot <<EOF
DROP USER IF EXISTS 'root'@'%';
CREATE USER 'root'@'%' IDENTIFIED BY 'password';
GRANT ALL PRIVILEGES ON * . * TO 'root'@'%';
ALTER USER 'root'@'%' IDENTIFIED BY 'password' PASSWORD EXPIRE NEVER;
ALTER USER 'root'@'%' IDENTIFIED WITH mysql_native_password BY 'password';
ALTER user 'root'@'%' IDENTIFIED by '$args_pwd';
ALTER user 'root'@'localhost' IDENTIFIED by '$args_pwd';
DROP USER IF EXISTS 'acore'@'localhost';
DROP USER IF EXISTS 'acore'@'127.0.0.1';
CREATE USER 'acore'@'localhost' IDENTIFIED BY 'acore';
CREATE USER 'acore'@'127.0.0.1' IDENTIFIED BY 'acore';
GRANT ALL PRIVILEGES ON * . * TO 'acore'@'localhost' WITH GRANT OPTION;
GRANT ALL PRIVILEGES ON * . * TO 'acore'@'127.0.0.1' WITH GRANT OPTION;
FLUSH PRIVILEGES;

DROP DATABASE IF EXISTS acore_auth;
DROP DATABASE IF EXISTS acore_characters;
DROP DATABASE IF EXISTS acore_world;
EOF
  if [ $? -eq 0 ]; then
    logOut "mysql写入sql成功"
  else
    error "mysql写入sql失败"
  fi

    if [ -f "/azerothcore/apps/db_assembler/conf.dist.sh" ]; then
        \cp /azerothcore/apps/db_assembler/conf.dist.sh /azerothcore/apps/db_assembler/config.sh
    fi
    cd /azerothcore/apps/db_assembler && bash db_assembler.sh import-bases && logOut "import-bases成功" || error "import-bases失败"

  # 设置reamlist
  mysql -uroot <<EOF
use acore_auth;
update realmlist set address='$args_ip',name='$args_name';
INSERT INTO account_access(id,gmlevel) values(1,3);
EOF
  if [ $? -eq 0 ]; then
    logOut "mysql写入reamlist成功"
  else
    error "mysql写入reamlist失败"
  fi

  #复制配置文件
  \cp /azerothcore/env/dist/etc/authserver.conf.dist /azerothcore/env/dist/etc/authserver.conf
  \cp /azerothcore/env/dist/etc/worldserver.conf.dist /azerothcore/env/dist/etc/worldserver.conf
  echo '[worldserver]' >/azerothcore/env/dist/etc/worldserver.conf
  echo 'SOAP.Enabled = 1' >>/azerothcore/env/dist/etc/worldserver.conf
  echo 'SOAP.IP = "0.0.0.0"' >>/azerothcore/env/dist/etc/worldserver.conf

  #设置允许远程登录
  if [ ! -f "/etc/mysql/my.cnf.bak" ]; then
    cp /etc/mysql/my.cnf /etc/mysql/my.cnf.bak
  fi
  \cp /etc/mysql/my.cnf.bak /etc/mysql/my.cnf
  echo '[mysqld]' >>/etc/mysql/my.cnf
  echo 'bind-address            = 0.0.0.0' >>/etc/mysql/my.cnf
  service mysql restart
  checkProcess "in" "mysql_init"
}

function downloadData() {
    # checkProcess "downloadData" && return
    cd ~
    rm -f /root/data.zip
    if [ "$version" = 2 ]; then
        wget --no-check-certificate --timeout=10 --tries=2 -O data.zip http://hx.phasercn.com/client-data/releases/download/v15/data.zip && logOut "data下载成功" || error "data下载失败"
    elif [ "$version" = 1 ]; then
        wget --no-check-certificate --timeout=10 --tries=2 -O data.zip http://hx.phasercn.com/client-data/releases/download/v15/data.zip && logOut "data下载成功" || error "data下载失败"
    else
        wget --no-check-certificate --timeout=10 --tries=2 -O data.zip http://hx.phasercn.com/client-data/releases/download/v15/data.zip && logOut "data下载成功" || error "data下载失败"
    fi
    cd /azerothcore/env/dist/bin
    unzip -qo ~/data.zip && logOut "解压data成功" || error "解压data失败"
    checkProcess "in" "downloadData"
}

function v2ray_inst() {
  checkProcess "v2ray_inst" && return
  if [[ "$1" == "stop" ]]; then
    systemctl stop v2ray
    return
  fi
  # downurl=$(curl --silent --insecure --connect-timeout 10 --max-time 5 --retry 2 https://api.github.com/repos/v2fly/v2ray-core/releases/latest | grep browser_download_url | grep linux-64 | grep -v dgst | cut -d '"' -f4)
  # if [[ -n "${downurl}" ]]; then
  #     logOut "获取v2ray下载地址成功"
  # else
  #     error "获取v2ray下载地址失败"
  # fi
  downurl="http://hx.phasercn.com/client-data/v2ray-linux-64.zip"
  wget --no-check-certificate --timeout=10 --tries=2 -c -O v2ray-linux-64.zip $downurl && logOut "v2ray下载成功" || error "v2ray下载失败"
  unzip -qo v2ray-linux-64.zip -d /usr/local/v2ray
  # 需要添加自己的代理json到这个
  echo '#!/bin/bash
source /etc/profile
cd /usr/local/v2ray
./v2ray run -config ../proxy.json
' >/usr/local/v2ray/v2rayRun
  chmod +x /usr/local/v2ray/v2rayRun
  ln -sf /usr/local/v2ray/v2ray /usr/bin/v2ray
  echo '[Unit]
Description=v2ray
After=network.target

[Service]
User=root
ExecStart=/usr/local/v2ray/v2rayRun
ExecStop=/bin/kill $MAINPID
Restart=always
RestartSec=10

[Install]
WantedBy=multi-user.target' >/etc/systemd/system/v2ray.service
  v2ray_start
  checkProcess "in" "v2ray_inst"
}

function v2ray_start(){
  systemctl daemon-reload && systemctl enable v2ray && systemctl restart v2ray
  sleep 1s
  check=$(systemctl is-active v2ray)
  if [[ "${check}" != "active" ]]; then
    error "v2ray启动失败"
  fi

  gitProxy "start"
}

function gitProxy() {
  if [[ "$1" == "start" ]]; then
    # socket代理
    git config --global http.proxy http://127.0.0.1:10809
    git config --global https.proxy https://127.0.0.1:10809
    git config --global http.sslVerify false

    # set proxy config via profie.d - should apply for all users
    export http_proxy="http://127.0.0.1:10809/"
    export https_proxy="http://127.0.0.1:10809/"
    export ftp_proxy="http://127.0.0.1:10809/"
    export no_proxy="127.0.0.1,localhost"
    # For curl
    export HTTP_PROXY="http://127.0.0.1:10809/"
    export HTTPS_PROXY="http://127.0.0.1:10809/"
    export FTP_PROXY="http://127.0.0.1:10809/"
    export NO_PROXY="127.0.0.1,localhost"
  else
    #重置代理
    git config --global --unset http.proxy
    git config --global --unset https.proxy
    unset http_proxy
    unset https_proxy
    unset ftp_proxy
    unset no_proxy
    unset HTTP_PROXY
    unset HTTPS_PROXY
    unset FTP_PROXY
    unset NO_PROXY
  fi
}

main() {
    rm ~/inst*.lock
    touch ~/install.lock
    cd ~
    echo `date +"%Y-%m-%d %H:%M:%S" ` 'start' >> ~/install.lock
    logOut "更新时区"
    timedatectl set-timezone Asia/Shanghai
    echo `date +"%Y-%m-%d %H:%M:%S" ` 'setEnv' >> ~/install.lock
    logOut "安装包"
    package_init
#    logOut "安装代理并且启动"
#    v2ray_inst
#    v2ray_start
    logOut "配置防火墙"
    firewall
    echo `date +"%Y-%m-%d %H:%M:%S" ` 'downloadSrc' >> ~/install.lock
    logOut "下载包"
    install
    echo `date +"%Y-%m-%d %H:%M:%S" ` 'compiler' >> ~/install.lock
    logOut "配置环境和编译器"
    setEnvAndcompiler
    echo `date +"%Y-%m-%d %H:%M:%S" ` 'setMysql' >> ~/install.lock
    logOut "mysql写入sql"
    mysql_init
    echo `date +"%Y-%m-%d %H:%M:%S" ` 'downloadMap' >> ~/install.lock
    logOut "下载data并且解压"
    downloadData
#    logOut "关闭代理"
#    v2ray_inst "stop"
#    gitProxy "stop"
    echo `date +"%Y-%m-%d %H:%M:%S" ` 'success' >> ~/install.lock
    logOut "安装完成"

    echo "$args_ip" >> ~/install_ip.lock
    echo "$args_pwd" >> ~/install_pwd.lock
    echo "$args_name" >> ~/install_name.lock
    echo "$version" >> ~/install_version.lock

}

main $@
